package pokerserver.core.network;

import common.GameAction;
import common.Message;
import pokerserver.core.ServerModel;

/**
 * A protocol which interprets a Message from a client, so that the
 * communication actually does something.
 * 
 */
public class ServerProtocol {

	private static ServerModel model = ServerModel.getInstance();

	/**
	 * Processes the incoming message from the client. Returns null if the
	 * incoming message does not ask for a reply. Also forwards the ServerThread
	 * that received the message.
	 * 
	 * @param input
	 */
	public static Message processMessage(ServerThread client, Message message) {
		switch (message.getType()) {

		/*
		 * Case 0: Ping. A client wishes to have updated game data sent to them.
		 */
		case 0:
			return model.getGameStateMessage(client);

			/*
			 * Case 1: Connect. A client wishes to connect. The value of the
			 * Message should be the nickname the player has chosen. No other
			 * details will need to be entered as the server already has created
			 * the player in ServerListener.
			 * 
			 * The server should return an empty message.
			 */
		case 1:
			if (message.getValue() instanceof String) {
				model.setNickname(client, (String) message.getValue());
				return new Message("Server", 1, null);
			}
			break;

		/*
		 * Case 2: Start game. The host (i.e. player with position one de facto)
		 * has pressed the start button. After this, no more players will be
		 * allowed to join the game.
		 * 
		 * The server should return a boolean signifying if the game was started
		 * or not.
		 */
		case 2:
			boolean hasGameStarted = model.startGame(client);
			return new Message("Server", 2, hasGameStarted);

			/*
			 * Case 3: A client wishes to know the current state of the game.
			 * 
			 * The server should return an updated GameState
			 */
		case 3:
			if (message.getValue() instanceof String) {
				return model.getGameStateMessage(client);
			}
			break;

		/*
		 * Case 4: A client wishes to perform an action. The incoming message
		 * value should be a GameAction.
		 */
		case 4:
			if (message.getValue() instanceof GameAction) {
				model.doAction(client, (GameAction) message.getValue());
				return model.getGameStateMessage(client);
			} else if (message.getValue() instanceof Integer) {
				int bet = Integer.parseInt(message.getValue().toString());
				model.doAction(client, GameAction.BET, bet);
				return model.getGameStateMessage(client);
			}
			break;

		}
		return new Message("Server", -1, "Error");

	}
}
